package com.ffcs.web.utils;

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.apache.log4j.Logger;



public class XMLTool {
	
	private static Logger logger = Logger.getLogger(XMLTool.class);
	
	public static Object xml2object(String xml,Class cla){
        try {
			JAXBContext jc = JAXBContext.newInstance(cla);
			Unmarshaller unma = jc.createUnmarshaller();
			return  unma.unmarshal(new StringReader(xml));
		} catch (JAXBException e) {
			logger.error("解析成Object出错，异常堆栈："+ExceptionUtils.getDetailMsg(e));
			throw new RuntimeException(e);
		}
	}
	
	public static String object2xml(Object obj,Class cla){
		try {
			StringWriter writer = new StringWriter();
			JAXBContext jc = JAXBContext.newInstance(cla);
			Marshaller ma = jc.createMarshaller();
            //ma.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, false);
			ma.marshal(obj, writer);
			writer.close();
			return writer.toString();
		} catch (Exception e) {
			logger.error("解析成字符串出错，异常堆栈："+ExceptionUtils.getDetailMsg(e));
			throw new RuntimeException(e);
		}
	}
}
